<template>
  <div class="mind-map-nav">
    <!-- 触发按钮 -->
    <el-button 
      class="mindmap-trigger"
      @click="visible = true"
      circle
    >
      <el-icon><Share /></el-icon>
    </el-button>

    <!-- 思维导图全屏 -->
    <el-dialog
      v-model="visible"
      fullscreen
      :show-close="false"
      class="mindmap-dialog"
    >
      <div class="mindmap-container">
        <!-- 顶部控制 -->
        <div class="mindmap-header">
          <h2>
            <el-icon><Share /></el-icon>
            功能思维导图
          </h2>
          <div class="header-controls">
            <el-button-group>
              <el-button @click="handleZoomIn">
                <el-icon><ZoomIn /></el-icon>
              </el-button>
              <el-button @click="handleZoomOut">
                <el-icon><ZoomOut /></el-icon>
              </el-button>
              <el-button @click="handleResetView">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-button-group>
            <el-button @click="visible = false">
              <el-icon><Close /></el-icon>
              关闭
            </el-button>
          </div>
        </div>

        <!-- SVG思维导图 -->
        <div class="mindmap-content" @wheel="handleWheel">
          <svg 
            :width="svgWidth" 
            :height="svgHeight"
            :viewBox="`0 0 ${svgWidth} ${svgHeight}`"
            class="mindmap-svg"
          >
            <!-- 连接线 -->
            <g class="connections">
              <path
                v-for="(line, index) in connectionLines"
                :key="'line-' + index"
                :d="line.path"
                :stroke="line.color"
                stroke-width="2"
                fill="none"
                opacity="0.3"
              />
            </g>

            <!-- 节点 -->
            <g class="nodes">
              <!-- 中心节点 -->
              <g class="center-node" :transform="`translate(${centerX}, ${centerY})`">
                <circle
                  r="80"
                  :fill="'url(#centerGradient)'"
                  stroke="white"
                  stroke-width="3"
                  @click="navigateTo({ path: '/dashboard' })"
                  class="node-circle"
                />
                <text
                  text-anchor="middle"
                  dy="5"
                  fill="white"
                  font-size="20"
                  font-weight="bold"
                >
                  Big-ERP
                </text>
              </g>

              <!-- 模块节点 -->
              <g 
                v-for="(module, index) in modules" 
                :key="module.key"
                :transform="`translate(${getModulePosition(index).x}, ${getModulePosition(index).y})`"
                class="module-node"
              >
                <circle
                  r="60"
                  :fill="`url(#gradient-${index})`"
                  stroke="white"
                  stroke-width="2"
                  @click="expandModule(module)"
                  class="node-circle"
                />
                <text
                  text-anchor="middle"
                  dy="5"
                  fill="white"
                  font-size="14"
                  font-weight="600"
                >
                  {{ module.title }}
                </text>
                <text
                  text-anchor="middle"
                  dy="25"
                  fill="rgba(255,255,255,0.8)"
                  font-size="11"
                >
                  {{ module.children.length }}个功能
                </text>
              </g>

              <!-- 功能子节点（展开时） -->
              <template v-if="expandedModule">
                <g 
                  v-for="(func, index) in expandedModule.children" 
                  :key="func.path"
                  :transform="`translate(${getFunctionPosition(index).x}, ${getFunctionPosition(index).y})`"
                  class="function-node"
                >
                  <circle
                    r="35"
                    :fill="expandedModule.color"
                    fill-opacity="0.8"
                    stroke="white"
                    stroke-width="1.5"
                    @click="navigateTo(func)"
                    class="node-circle"
                  />
                  <text
                    text-anchor="middle"
                    dy="5"
                    fill="white"
                    font-size="11"
                  >
                    {{ func.title }}
                  </text>
                </g>
              </template>
            </g>

            <!-- 渐变定义 -->
            <defs>
              <linearGradient id="centerGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" stop-color="#667eea" />
                <stop offset="100%" stop-color="#764ba2" />
              </linearGradient>
              <linearGradient 
                v-for="(module, index) in modules" 
                :key="'grad-' + index"
                :id="`gradient-${index}`" 
                x1="0%" 
                y1="0%" 
                x2="100%" 
                y2="100%"
              >
                <stop offset="0%" :stop-color="getGradientColors(module.gradient).start" />
                <stop offset="100%" :stop-color="getGradientColors(module.gradient).end" />
              </linearGradient>
            </defs>
          </svg>
        </div>

        <!-- 底部提示 -->
        <div class="mindmap-footer">
          <div class="footer-info">
            <el-icon><InfoFilled /></el-icon>
            <span>点击模块查看详细功能 · 点击功能直接跳转 · 滚轮缩放</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  Share, ZoomIn, ZoomOut, Refresh, Close, InfoFilled
} from '@element-plus/icons-vue'

const router = useRouter()

const visible = ref(false)
const svgWidth = ref(1600)
const svgHeight = ref(900)
const centerX = ref(800)
const centerY = ref(450)
const scale = ref(1)
const expandedModule = ref(null)

// 模块数据（简化版）
const modules = ref([
  { 
    key: 'lowcode', 
    title: '低代码', 
    gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    color: '#667eea',
    children: [
      { path: '/lowcode/form-designer', title: '表单设计' },
      { path: '/lowcode/page-designer', title: '页面设计' },
      { path: '/lowcode/ai-assistant', title: 'AI助手' },
      { path: '/lowcode/code-generator', title: '代码生成' }
    ]
  },
  { 
    key: 'contract', 
    title: '合同', 
    gradient: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    color: '#f093fb',
    children: [
      { path: '/contract/list', title: '合同列表' },
      { path: '/contract/approval', title: '合同审批' },
      { path: '/contract/statistics', title: '合同统计' }
    ]
  },
  { 
    key: 'asset', 
    title: '资产', 
    gradient: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    color: '#4facfe',
    children: [
      { path: '/asset/list', title: '资产列表' },
      { path: '/asset/inventory', title: '资产盘点' },
      { path: '/asset/transfer', title: '资产调拨' }
    ]
  },
  { 
    key: 'equipment', 
    title: '设备', 
    gradient: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    color: '#43e97b',
    children: [
      { path: '/equipment/ledger', title: '设备台账' },
      { path: '/equipment/oee', title: '设备OEE' },
      { path: '/equipment/maintenance', title: '维保计划' }
    ]
  },
  { 
    key: 'sales', 
    title: '销售', 
    gradient: 'linear-gradient(135deg, #fa709a 0%, #fee140 100%)',
    color: '#fa709a',
    children: [
      { path: '/sales/orders', title: '销售订单' },
      { path: '/sales/customer-crm', title: '客户CRM' }
    ]
  },
  { 
    key: 'purchase', 
    title: '采购', 
    gradient: 'linear-gradient(135deg, #30cfd0 0%, #330867 100%)',
    color: '#30cfd0',
    children: [
      { path: '/purchase/orders', title: '采购订单' },
      { path: '/purchase/suppliers', title: '供应商' }
    ]
  }
])

// 获取模块位置（圆形分布）
const getModulePosition = (index) => {
  const radius = 300
  const angleStep = (2 * Math.PI) / modules.value.length
  const angle = angleStep * index - Math.PI / 2 // -90度从顶部开始
  
  return {
    x: centerX.value + Math.cos(angle) * radius,
    y: centerY.value + Math.sin(angle) * radius
  }
}

// 获取功能位置（围绕模块）
const getFunctionPosition = (index) => {
  if (!expandedModule.value) return { x: 0, y: 0 }
  
  const moduleIndex = modules.value.findIndex(m => m.key === expandedModule.value.key)
  const modulePos = getModulePosition(moduleIndex)
  
  const radius = 120
  const angleStep = (2 * Math.PI) / expandedModule.value.children.length
  const angle = angleStep * index
  
  return {
    x: modulePos.x + Math.cos(angle) * radius,
    y: modulePos.y + Math.sin(angle) * radius
  }
}

// 连接线
const connectionLines = computed(() => {
  const lines = []
  
  // 中心到模块的连接线
  modules.value.forEach((module, index) => {
    const pos = getModulePosition(index)
    const gradient = getGradientColors(module.gradient)
    lines.push({
      path: `M ${centerX.value} ${centerY.value} Q ${(centerX.value + pos.x) / 2} ${(centerY.value + pos.y) / 2} ${pos.x} ${pos.y}`,
      color: gradient.start
    })
  })
  
  // 模块到功能的连接线
  if (expandedModule.value) {
    const moduleIndex = modules.value.findIndex(m => m.key === expandedModule.value.key)
    const modulePos = getModulePosition(moduleIndex)
    
    expandedModule.value.children.forEach((func, index) => {
      const funcPos = getFunctionPosition(index)
      lines.push({
        path: `M ${modulePos.x} ${modulePos.y} L ${funcPos.x} ${funcPos.y}`,
        color: expandedModule.value.color
      })
    })
  }
  
  return lines
})

// 获取渐变颜色
const getGradientColors = (gradient) => {
  const match = gradient.match(/#[0-9a-f]{6}/gi)
  return {
    start: match[0] || '#667eea',
    end: match[1] || '#764ba2'
  }
}

// 展开模块
const expandModule = (module) => {
  if (expandedModule.value?.key === module.key) {
    expandedModule.value = null
  } else {
    expandedModule.value = module
  }
}

// 导航
const navigateTo = (item) => {
  router.push(item.path)
  visible.value = false
  ElMessage.success('跳转成功')
}

// 缩放
const handleZoomIn = () => {
  if (scale.value < 2) {
    scale.value += 0.2
  }
}

const handleZoomOut = () => {
  if (scale.value > 0.5) {
    scale.value -= 0.2
  }
}

const handleResetView = () => {
  scale.value = 1
  expandedModule.value = null
}

const handleWheel = (event) => {
  event.preventDefault()
  if (event.deltaY < 0) {
    handleZoomIn()
  } else {
    handleZoomOut()
  }
}

// 全局快捷键
const handleGlobalKeydown = (event) => {
  // Ctrl + M 打开思维导图
  if ((event.ctrlKey || event.metaKey) && event.key === 'm') {
    event.preventDefault()
    visible.value = !visible.value
  }
}

onMounted(() => {
  document.addEventListener('keydown', handleGlobalKeydown)
})

onBeforeUnmount(() => {
  document.removeEventListener('keydown', handleGlobalKeydown)
})
</script>

<style scoped>
.mindmap-trigger {
  position: fixed;
  right: 30px;
  bottom: 420px;
  width: 50px;
  height: 50px;
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
  border: none;
  box-shadow: 0 4px 16px rgba(250, 112, 154, 0.4);
  z-index: 1000;
  transition: all 0.3s;
}

.mindmap-trigger:hover {
  transform: scale(1.1);
  box-shadow: 0 6px 20px rgba(250, 112, 154, 0.5);
}

:deep(.mindmap-dialog .el-dialog__body) {
  padding: 0;
  background: #1a1a2e;
}

.mindmap-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: radial-gradient(circle at 50% 50%, #16213e 0%, #0f1419 100%);
}

.mindmap-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 40px;
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.mindmap-header h2 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: white;
  font-size: 20px;
}

.header-controls {
  display: flex;
  gap: 15px;
}

.mindmap-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.mindmap-svg {
  transition: transform 0.3s;
}

.node-circle {
  cursor: pointer;
  transition: all 0.3s;
}

.node-circle:hover {
  filter: brightness(1.2);
  stroke-width: 4;
}

.mindmap-footer {
  padding: 15px 40px;
  background: rgba(255, 255, 255, 0.05);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.footer-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
  justify-content: center;
}

/* 淡入淡出 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>

